package top.zhangjianyong.utils;

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ： zhangjianyong
 * @date ： 2022/12/21 3:44 PM
 */
public class RegexUtil {

    /**
     * 正则匹配一个值
     *
     * @param body
     * @param regex
     * @param group
     * @return
     */
    public static String matcherFirst(String body, String regex, int group) {
        // 创建 Pattern 对象
        Pattern r = Pattern.compile(regex);
        // 现在创建 matcher 对象
        Matcher m = r.matcher(body);
        if (m.find()) {
            return m.group(group);
        }
        return null;
    }

    /**
     * 正则匹配多个值
     *
     * @param body
     * @param regex
     * @param group
     * @return
     */
    public static List<String> matcherAllFirst(String body, String regex, int group) {
        // 创建 Pattern 对象
        Pattern r = Pattern.compile(regex);
        // 现在创建 matcher 对象
        Matcher m = r.matcher(body);
        if (m.find()) {
            List<String> list = new ArrayList<>();
            for (int i = 1; i <= group; i++) {
                list.add(m.group(i));
            }
            return list;
        }
        return null;
    }

    public static List<String> matcher(String body, String regex, int group) {
        List<String> list = new ArrayList<>();
        // 创建 Pattern 对象
        Pattern r = Pattern.compile(regex);
        // 现在创建 matcher 对象
        Matcher m = r.matcher(body);
        while (m.find()) {
            list.add(m.group(group));
        }
        return list;
    }

    public static boolean matches(String body, String regex) {
        Pattern r = Pattern.compile(regex);
        return r.matcher(body).matches();
    }

    public static List<String> matchesAll(String body, String regex) {
        Pattern r = Pattern.compile(regex);
        Matcher matcher = r.matcher(body);
        List<String> list = new ArrayList<>();
        if (matcher.find()) {
            int count = matcher.groupCount();
            for (int i = 0; i <= count; i++) {
                list.add(matcher.group(i));
            }
        }
        return list;
    }

    public static void main(String[] args) {
        String body = "http://www.baidu.com/2/2/a/f?ww=e&d=1";
        String regex = "(http.?):";
        int group = 1;
        String matcher = matcherFirst(body, regex, group);
        System.out.println(matcher);
        List<String> matcher1 = matcher(body, regex, group);
        System.out.println(JSONObject.toJSONString(matcher1));
    }


}
